var shopCart = {};

var shoppingcartHelper = function() {
	var SHOPPINGCART_URL = "/PictureCentral/shoppingCart/";
	var SHOPPINGCART_DIV = "shoppingCartContent";
	
	function clearDiv() {
		var div = document.getElementById(SHOPPINGCART_DIV);
		div.innerHTML ="";
	};
	
	function updateDiv(result) {
		var div = document.getElementById(SHOPPINGCART_DIV);
		div.innerHTML = result.responseText;
	}
	
	return {
	   addToCart : function(pictureId) {
		   Ext.Ajax.request({
			   url: SHOPPINGCART_URL+'add',
			   params: { itemID: pictureId },
			   success: function() {
				   shoppingcartHelper.viewCart();
			   },
			   failure: function() { Ext.Msg.alert('Failure:', 'Cannot add the item to shopping cart !!'); }
		   });
	   },

	   removeFromCart : function(pictureId) {
		   Ext.Ajax.request({
			   url: SHOPPINGCART_URL+'remove',
			   params: { itemID: pictureId },
			   success: function() {
				   shoppingcartHelper.viewCart();
			   },
			   failure: function() { Ext.Msg.alert('Failure:', 'Cannot remove the item from shopping cart !!'); }
		   });
	   },

	   viewCart : function() {
		   Ext.Ajax.request({
			   url: SHOPPINGCART_URL+'view',
			   success: function(result, request) {
			   		updateDiv(result);
			   },
			   failure: function() { Ext.Msg.alert('Failure:', 'Error while viewing shopping cart !!'); }
		   });		   
	   },

	   downloadPicture: function(pictureId) {
		   Ext.Ajax.request({
			   url: SHOPPINGCART_URL+'download',
			   params: { id: pictureId }//,
			   /*success: function(result, request) {
				   
				   return shopCart.URL+'orderedPictures';
			   },
			   failure: function() { Ext.Msg.alert('Failure:', 'Error while downloading the picture !!'); }
			   */
		   });
	   },
	   
	   displayCart: function() {
		   shoppingcartHelper.viewCart();
		   return SHOPPINGCART_URL+'view';
	   },

	   checkOutCart : function() {
		   shoppingCartFormHandler.checkOutForm();
	   },

	   clearCart : function() {
		   Ext.Ajax.request({
			   url: SHOPPINGCART_URL+'clear',
			   success: function() {
			   		shoppingcartHelper.viewCart();
			   },
			   failure: function() { Ext.Msg.alert('Failure:', 'Error when trying to clear shopping cart !!'); }
		   });
	   }
  };
}();

var shoppingCartFormHandler = function() {
	var win = null;
	function createWindow(loginPanel) {
		win = new Ext.Window({
	        title:'Shopping Cart Checkout', 
	        layout:'fit',
	        width:400,
	        height:420,
	        resizable: false,
	        plain: true,
	        border: false,
	        modal: true,
	        items: [loginPanel]
		});
		return win;
	};
	
	function createFormPanel() {
		var cardtypes = new Ext.data.SimpleStore({
			fields: ['cardtypeshort', 'cardtypename'],
			data : [['Visa','Visa'],['Amex','American Express']]
			});
		var months = new Ext.data.SimpleStore({
			fields: ['month', 'monthname'],
			data : [['01','January'],['02','February'],['03','March'],['04','April'],['05','May'],['06','June'],['07','July'],['08','August'],['09','September'],['10','October'],['11','November'],['12','December']]
			});
		var years = new Ext.data.SimpleStore({
			fields: ['year', 'yearlabel'],
			data : [['2009','2009'],['2010','2010'],['2011','2011'],['2012','2012'],['2013','2013'],['2014','2014'],['2015','2015'],['2016','2016'],['2017','2017'],['2018','2018'],['2019','2019'],['2020','2020'],['2021','2021'],['2022','2022']]
			});
		var states = new Ext.data.SimpleStore({
			fields: ['stateshort', 'statename'],
			data : [['AL','Alabama'],['AK','Alaska'],['AZ','Arizona'],['AR','Arkansas'],['CA','California'],['CO','Colorado'],['CT','Connecticut'],['DE','Delaware'],['DC','District of Columbia'],['FL','Florida'],['GA','Georgia'],['HI','Hawaii'],['ID','Idaho'],['IL','Illinois'],['IN','Indiana'],['IA','Iowa'],['KS','Kansas'],['KY','Kentucky'],['LA','Louisiana'],['ME','Maine'],['MD','Maryland'],['MA','Massachusetts'],['MI','Michigan'],['MN','Minnesota'],['MS','Mississippi'],['MO','Missouri'],['MT','Montana'],['NE','Nebraska'],['NV','Nevada'],['NH','New Hampshire'],['NJ','New Jersey'],['NM','New Mexico'],['NY','New York'],['NC','North Carolina'],['ND','North Dakota'],['OH','Ohio'],['OK','Oklahoma'],['OR','Oregon'],['PA','Pennsylvania'],['RI','Rhode Island'],['SC','South Carolina'],['SD','South Dakota'],['TN','Tennessee'],['TX','Texas'],['UT','Utah'],['VT','Vermont'],['VA','Virginia'],['WA','Washington'],['WV','West Virginia'],['WI','Wisconsin'],['WY','Wyoming']]
			});
		var countries = new Ext.data.SimpleStore({
			fields: ['countryshort', 'countryname'],
			data : [['US','United States'],['CA','Canada']]
			});
	    var formPanel =  new Ext.FormPanel({ 
	        labelWidth:80,
	        url:'/PictureCentral/payPal/visaPayment', 
	        frame:true, 
	        defaultType:'textfield',
		    monitorValid:true,
	        items:[{ 
                	xtype: 'combo',
                	name: 'cardtype',
                	fieldLabel: 'Card type',
                	mode: 'local',
                	store: cardtypes,
                	displayField:'cardtypeshort',
                	editable:true,
                	width: 130
        		},{
	        		fieldLabel:'Card Number', 
	        		name:'acct',
	        		allowBlank:false 
            	},{
	                xtype: 'combo',
	                name: 'expiredmonth',
	                fieldLabel: 'Expired month',
	                mode: 'local',
	                store: months,
	                displayField:'month',
	                editable:true,
	                width: 130
            	},{
	                xtype: 'combo',
	                name: 'expiredyear',
	                fieldLabel: 'Expired year',
	                mode: 'local',
	                store: years,
	                displayField:'year',
	                editable:true,
	                width: 130
            	},{
	        		fieldLabel:'Firstname', 
	                name:'firstname',
	                allowBlank:false 
	            },{
	            	fieldLabel:'Lastname', 
	                name:'lastname',
	                allowBlank:false 
	            },{
	                fieldLabel:'Address', 
	                name:'address',
	                allowBlank:false 
	            },{ 
	                fieldLabel:'City', 
	                name:'city',
	                allowBlank:false 
	            },{ 
	                xtype: 'combo',
	                name: 'state',
	                fieldLabel: 'State',
	                mode: 'local',
	                store: states,
	                displayField:'stateshort',
	                editable:true,
	                width: 130
	            },{ 
	            	fieldLabel:'Zip code', 
	                name:'zipcode',
	                allowBlank:false 
	            },{
	                xtype: 'combo',
	                name: 'countrycode',
	                fieldLabel: 'Country',
	                mode: 'local',
	                store: countries,
	                displayField:'countryshort',
	                editable:true,
	                width: 130
	            }],
      	        buttons:[
                    new Ext.Button({
            			text:'Submit To Pay',
            			tabIndex:0,
            			formBind: true,	 
            			handler:function(){ 
                    		formPanel.getForm().submit({ 
            		    		method:'POST', 
            		    		success: function(form, action){
                    			    var obj = Ext.util.JSON.decode(action.response.responseText);
                    			    window.location = obj.url;
            		    	    },
            		    		failure:function(form, action){ 
           		    				var obj = Ext.util.JSON.decode(action.response.responseText); 
           		    				Ext.Msg.alert('Submit Failed!', obj.errors); 
                            	} 
            		    	}); 
                    	} 
            		}),
                    new Ext.Button({
            			text:'Cancel',
            			tabIndex:1,
            			formBind: false,	 
            			handler:function(){ 
                    		win.close();
                    	} 
            		})
                    ] 
	    });
	    return formPanel;
	}
	
	return {
		checkOutForm : function() {
		   var loginWin =createWindow(createFormPanel());
		   loginWin.show();		   
	    }		
	};	
}();


shopCart.URL = '/PictureCentral/shoppingCart/';

shopCart.orderStore = function(action, jsonName, params) {
	
    if(!params || params == null) { 
    	params = [];
    }

    var attributes = [ 
        {name: 'orderID'},
        {name: 'createdOn'},
        {name: 'login'},
        {name: 'totalPrice'}, 
        {name: 'status'} 
    ];
    
    // create the Data Store 
    var dataStore = new Ext.data.Store({ 
        autoLoad: true, 
        url: shopCart.URL+action,
    	baseParams: params,
        reader: new Ext.data.JsonReader({ 
        	results: 'total', 
        	title: 'title',
        	root:jsonName, 
        	id:'id' 
           }, 
           attributes
        )
    });
    return dataStore;
};

shopCart.orderList = function() {
    var urlQuery = location.search;
	var href = shopCart.URL+'listOrders'+urlQuery;
	var idx = urlQuery.indexOf('?');
	var params = [];
	if(idx >= 0) { 
	  var qry = urlQuery.substring(idx+1);
	  params = Ext.urlDecode(qry);
	}

	var pictureGrid = document.getElementById('picture-grid');
	pictureGrid.innerHTML ="";
	var tableId = 'orderListGridPanel';
	pictureHelper.setTableId(tableId);
    // create the Data Store 
	var ds = shopCart.orderStore('listOfOrders','row', params);

	var cm = new Ext.grid.ColumnModel({
        columns: [ 
          {header: "Order ID", align:'center', dataIndex: 'orderID'}, 
          {header: "Order Date", align:'left', dataIndex: 'createdOn'}, 
      	  {header: "Login", align:'left', dataIndex: 'login'},
          {header: "Total Price (USD)", align:'left', dataIndex: 'totalPrice'},
          {header: "Status", width: 50, align:'left', dataIndex: 'status'}
        ],
        defaultSortable: true
    });
	
    // create the grid 
    var grid = new Ext.grid.EditorGridPanel({ 
        ds: ds, 
        cm: cm,
        title: ' ',
        id: tableId,
        renderTo:'picture-grid', 
        stripeRows: true,
        autoHeight: true,
        autoWidth: true,
        //width:720, 
        height:480 
    });  	
    ds.on('load', function(store, records, options) { 
    	grid.setTitle(store.reader.jsonData.title);
    });
    return href;
};

shopCart.pictureOrderListColumns = new Ext.grid.ColumnModel({
	columns: [ 
	          {header: "", align:'center', width: 100, dataIndex: 'thumbnailPath', renderer:pictureRenders.imageActionRender}, 
	          {header: "Name", width: 100, align:'left', dataIndex: 'name'}, 
	          {header: "", width: 25, align:'left', dataIndex: 'id', renderer:pictureRenders.downloadActionRender},
	          {header: "Description",  width: 120, align:'left', dataIndex: 'description'}, 
	          {header: "Category", width: 100, aling:'left', dataIndex: 'category'},
	          {header: "Price", width: 50, align:'left', dataIndex: 'price'},
	          {header: "Created On", width: 100, align:'left', dataIndex: 'createdOn'}
	],
	defaultSortable: true
});

